<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>仪表盘</h1>
      <p>欢迎回来，{{ authStore.user?.username }}！</p>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon project">
          <el-icon><Folder /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ stats.totalProjects }}</h3>
          <p>总项目数</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon task">
          <el-icon><List /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ stats.totalTasks }}</h3>
          <p>总任务数</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon issue">
          <el-icon><Warning /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ stats.totalIssues }}</h3>
          <p>总问题数</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon report">
          <el-icon><Document /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ stats.totalReports }}</h3>
          <p>总日报数</p>
        </div>
      </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-grid">
      <!-- 项目状态分布 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>项目状态分布</h3>
        </div>
        <div class="chart-content">
          <div ref="projectStatusChart" class="chart"></div>
        </div>
      </div>
      
      <!-- 任务完成趋势 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>任务完成趋势</h3>
        </div>
        <div class="chart-content">
          <div ref="taskTrendChart" class="chart"></div>
        </div>
      </div>
    </div>
    
    <!-- 快速操作和最近活动 -->
    <div class="bottom-grid">
      <!-- 快速操作 -->
      <div class="quick-actions">
        <h3>快速操作</h3>
        <div class="action-buttons">
          <el-button type="primary" @click="createProject">
            <el-icon><Plus /></el-icon>
            创建项目
          </el-button>
          <el-button type="success" @click="createTask">
            <el-icon><Plus /></el-icon>
            创建任务
          </el-button>
          <el-button type="warning" @click="reportIssue">
            <el-icon><Plus /></el-icon>
            报告问题
          </el-button>
          <el-button type="info" @click="createReport">
            <el-icon><Plus /></el-icon>
            写日报
          </el-button>
        </div>
      </div>
      
      <!-- 最近活动 -->
      <div class="recent-activities">
        <h3>最近活动</h3>
        <div class="activity-list">
          <div class="activity-item" v-for="activity in recentActivities" :key="activity.id">
            <div class="activity-icon">
              <el-icon><component :is="getActivityIcon(activity.type)" /></el-icon>
            </div>
            <div class="activity-content">
              <p class="activity-text">{{ activity.description }}</p>
              <span class="activity-time">{{ formatTime(activity.createdAt) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 我的任务 -->
    <div class="my-tasks">
      <div class="section-header">
        <h3>我的任务</h3>
        <el-link type="primary" @click="viewAllTasks">查看全部</el-link>
      </div>
      <div class="task-list">
        <div class="task-item" v-for="task in myTasks" :key="task.id">
          <div class="task-priority" :class="task.priority"></div>
          <div class="task-content">
            <h4>{{ task.title }}</h4>
            <p>{{ task.description }}</p>
            <div class="task-meta">
              <el-tag :type="getTaskStatusType(task.status)" size="small">
                {{ task.status }}
              </el-tag>
              <span class="task-deadline">{{ formatDate(task.dueDate) }}</span>
            </div>
          </div>
          <div class="task-actions">
            <el-button size="small" @click="viewTask(task.id)">查看</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

import * as echarts from 'echarts'
import dayjs from 'dayjs'
import {
  Folder,
  List,
  Warning,
  Document,
  Plus,


} from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()


const projectStatusChart = ref<HTMLElement>()
const taskTrendChart = ref<HTMLElement>()

// 统计数据
const stats = ref({
  totalProjects: 0,
  totalTasks: 0,
  totalIssues: 0,
  totalReports: 0
})

// 我的任务
const myTasks = ref<any[]>([])

// 最近活动
const recentActivities = ref([
  {
    id: 1,
    type: 'task',
    description: '完成了任务：实现用户登录功能',
    createdAt: new Date(Date.now() - 1000 * 60 * 30)
  },
  {
    id: 2,
    type: 'project',
    description: '创建了项目：项目管理系统',
    createdAt: new Date(Date.now() - 1000 * 60 * 60 * 2)
  },
  {
    id: 3,
    type: 'issue',
    description: '报告了问题：登录页面样式异常',
    createdAt: new Date(Date.now() - 1000 * 60 * 60 * 4)
  },
  {
    id: 4,
    type: 'report',
    description: '提交了日报：2024-01-15',
    createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24)
  }
])

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 项目状态分布饼图
    if (projectStatusChart.value) {
      const chart1 = echarts.init(projectStatusChart.value)
      chart1.setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '项目状态',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 5, name: '进行中' },
              { value: 3, name: '已完成' },
              { value: 2, name: '已暂停' },
              { value: 1, name: '已取消' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
    }
    
    // 任务完成趋势折线图
    if (taskTrendChart.value) {
      const chart2 = echarts.init(taskTrendChart.value)
      chart2.setOption({
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['新建任务', '完成任务']
        },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '新建任务',
            type: 'line',
            data: [5, 8, 12, 6, 10, 3, 7]
          },
          {
            name: '完成任务',
            type: 'line',
            data: [3, 6, 8, 9, 7, 5, 8]
          }
        ]
      })
    }
  })
}

// 加载数据
const loadData = async () => {
  try {
    // 加载统计数据
    stats.value = {
      totalProjects: 11,
      totalTasks: 45,
      totalIssues: 8,
      totalReports: 23
    }
    
    // 加载我的任务
    myTasks.value = [
      {
        id: 1,
        title: '实现用户认证功能',
        description: '完成用户登录、注册和权限验证',
        status: '进行中',
        priority: 'high',
        dueDate: new Date(Date.now() + 1000 * 60 * 60 * 24 * 3)
      },
      {
        id: 2,
        title: '设计数据库表结构',
        description: '设计用户、项目、任务等表结构',
        status: '已完成',
        priority: 'medium',
        dueDate: new Date(Date.now() - 1000 * 60 * 60 * 24)
      },
      {
        id: 3,
        title: '编写API文档',
        description: '编写后端API接口文档',
        status: '待开始',
        priority: 'low',
        dueDate: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7)
      }
    ]
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 获取活动图标
const getActivityIcon = (type: string) => {
  const icons: Record<string, any> = {
    task: List,
    project: Folder,
    issue: Warning,
    report: Document
  }
  return icons[type] || Document
}

// 获取任务状态类型
const getTaskStatusType = (status: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
  const types: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    '进行中': 'primary',
    '已完成': 'success',
    '已暂停': 'warning',
    '待开始': 'info'
  }
  return types[status] || 'info'
}

// 格式化时间
const formatTime = (date: Date) => {
  return dayjs(date).fromNow()
}

// 格式化日期
const formatDate = (date: Date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 快速操作
const createProject = () => {
  router.push('/projects/create')
}

const createTask = () => {
  router.push('/tasks/create')
}

const reportIssue = () => {
  router.push('/issues/create')
}

const createReport = () => {
  router.push('/reports/create')
}

const viewAllTasks = () => {
  router.push('/tasks/my')
}

const viewTask = (id: number) => {
  router.push(`/tasks/${id}`)
}

onMounted(() => {
  loadData()
  initCharts()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.dashboard-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #fff;
}

.stat-icon.project {
  background: #409eff;
}

.stat-icon.task {
  background: #67c23a;
}

.stat-icon.issue {
  background: #e6a23c;
}

.stat-icon.report {
  background: #909399;
}

.stat-content h3 {
  margin: 0 0 4px 0;
  font-size: 24px;
  color: #333;
}

.stat-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.chart-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-header {
  margin-bottom: 16px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.chart {
  height: 300px;
}

.bottom-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 24px;
}

.quick-actions,
.recent-activities {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.quick-actions h3,
.recent-activities h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #333;
}

.action-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.activity-list {
  max-height: 300px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
}

.activity-text {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #333;
}

.activity-time {
  font-size: 12px;
  color: #999;
}

.my-tasks {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.task-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  transition: all 0.3s;
}

.task-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.task-priority {
  width: 4px;
  height: 40px;
  border-radius: 2px;
}

.task-priority.high {
  background: #f56c6c;
}

.task-priority.medium {
  background: #e6a23c;
}

.task-priority.low {
  background: #67c23a;
}

.task-content {
  flex: 1;
}

.task-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #333;
}

.task-content p {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #666;
}

.task-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-deadline {
  font-size: 12px;
  color: #999;
}

.task-actions {
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .charts-grid {
    grid-template-columns: 1fr;
  }
  
  .bottom-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    grid-template-columns: 1fr;
  }
}
</style>